﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.DB;
using System.Data;
using System.Data.SqlClient;
using MaxLeaf.Common;

namespace MaxLeaf.DAL.Web2SCP
{
    class ImInvMasterDAL
    {
        private int Insert(DBAccess dbDestSCPCon, int intGoodsID, int intGoodsAttrID)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbDestSCPCon.CreateCondParam(new Dictionary<string, object>() { { "GoodsID", intGoodsID }, { "GoodsAttrID", intGoodsAttrID } });
            DataTable dtData = dbDestSCPCon.GetDataTable(string.Format("select * from ImInvMaster where {0}", kvp.Key), kvp.Value);
            if (dtData.Rows.Count == 0)
            {
                string strFinterID = GetFInterID(dbDestSCPCon);

                DataRow drData = dtData.NewRow();
                drData["FinterID"] = strFinterID;
                drData["GoodsID"] = intGoodsID;
                drData["GoodsAttrID"] = intGoodsAttrID;
                drData["Is_UsedAttr"] = 1;

                kvp = dbDestSCPCon.CreateParamSql("FinterID,GoodsID,GoodsAttrID,Is_UsedAttr", "ImInvMaster", drData, Common.LogStatus.Add, "FinterID");
                string strIdentity = dbDestSCPCon.GetValue(kvp.Key, kvp.Value);

                return CvtFunc.ToInt(drData["FinterID"]);
            }
            else {
                DataRow drData = dtData.Rows[0];
                drData["Is_UsedAttr"] = 1;
                kvp = dbDestSCPCon.CreateParamSql("Is_UsedAttr", "ImInvMaster", drData, Common.LogStatus.Update, "FinterID");
                string strIdentity = dbDestSCPCon.GetValue(kvp.Key, kvp.Value);

                return CvtFunc.ToInt(drData["FinterID"]);
            }

            

            
        }

        private string GetFInterID(DBAccess dbDestSCPCon)
        {
            using (DBAccess dbconID = new DBAccess(dbDestSCPCon.SCPFinterIDDB))
            {
                const int ImInvMaster = 20;
                return dbconID.GetValue("exec GetICFinteID @IsSave,@FBillType,@BillId output"
                   , new SqlParameter[] {
                        new SqlParameter("@IsSave", "1")
                        ,new SqlParameter("@FBillType",(ImInvMaster).ToString())
                        ,new SqlParameter("@BillID",SqlDbType.VarChar,50)
                    }
                   , "BillID");
            }
            
        }

        private void UpdateStockUnit(DBAccess dbDestSCPCon, int intGoodsID)
        {
            string strSql = @"update ImInvMaster  set stockunitid=g_u.measure_unit_id  from goods_main g 
                    inner join goods_unit_group g_u_g on g.unit_group_id=g_u_g.unit_group_id
                    inner join goods_measure_unit g_u on g_u.unit_group_id=g_u_g.unit_group_id
                    where g_u.measure_coefficient=1 and g.goods_id=ImInvMaster.goodsid  and ImInvMaster.goodsid=@goodsid";
            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@goodsid", intGoodsID.ToString()) });


            strSql =string.Format(@"update {0}..ImInvLoc  set stockunitid=i.stockunitid  from ImInvMaster i
                    where i.goodsid=@goodsid  and {0}..ImInvLoc.itemid=i.finterid"
                , dbDestSCPCon.SCPInvDB.Database
                );
            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@goodsid", intGoodsID.ToString()) });
        }


        internal void UpdateDelete(DBAccess dbDestSCPCon, int intGoodsID,bool blnDelete)
        {
//            string strSql = @"update ImInvMaster  set is_delete=@Delete  from goods_main g 
//                    where  g.goods_id=ImInvMaster.goodsid  and ImInvMaster.goodsid=@goodsid";
//            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@goodsid", intGoodsID.ToString()), new SqlParameter("@Delete", blnDelete.ToString()) });


//            strSql = string.Format(@"update {0}..ImInvLoc  set is_delete=i.is_delete  from ImInvMaster i
//                    where i.goodsid=@goodsid  and {0}..ImInvLoc.itemid=i.finterid"
            //                 , dbDestSCPCon.SCPInvDB
//                );
//            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@goodsid", intGoodsID.ToString()) });
        }

        internal void RefreshData(DBAccess dbDestSCPCon, int intGoodsID)
        {

            string strSql = @"
            select distinct a.goods_id, isnull(b.goods_attr_id,0) as goods_attr_id
            from dbo.goods_main a
            inner join dbo.goods_attribute b on a.goods_id=b.goods_id and a.goods_id=@GoodsID
                inner join dbo.goods_cat_attribute g_c_a on g_c_a.attr_id=b.attr_id  and g_c_a.is_buy_condition=1
        
            union
                select distinct a.goods_id,0 as goods_attr_id
                from dbo.goods_main a
                inner join dbo.goods_attribute b on a.goods_id=b.goods_id and a.goods_id=@GoodsID
                  where not exists(select g_c_a.* from dbo.goods_cat_attribute g_c_a where g_c_a.attr_id=b.attr_id  and g_c_a.is_buy_condition=1)
            union
                select distinct a.goods_id,0 as goods_attr_id
                from dbo.goods_main a

                  where not exists(select b.* from dbo.goods_attribute b where a.goods_id=b.goods_id)  and a.goods_id=@GoodsID
            ";
            DataTable dt = dbDestSCPCon.GetDataTable(strSql, new SqlParameter[] {
                new SqlParameter("@GoodsID",intGoodsID.ToString())
            });
            List<int> lstID = new List<int>();
            foreach (DataRow dr in dt.Rows)
            {
                lstID.Add(Insert(dbDestSCPCon, intGoodsID, CvtFunc.ToInt(dr["goods_attr_id"])));
            }

            strSql = "update ImInvMaster set Is_UsedAttr=0  where GoodsID=@GoodsID"
                + (lstID.Count > 0 ? string.Format(" and FinterID not in ({0})",string.Join(",",lstID.ToArray())) : string.Empty);
            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] {
                new SqlParameter("@GoodsID",intGoodsID.ToString())
            });

            UpdateStockUnit(dbDestSCPCon, intGoodsID);
        }
    }
}
